import 'package:flutter/material.dart';
import 'dart:async';
import '../routes.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../services/auth_service.dart';
import '../riverpod/photo_backup_notifier.dart';
import '../services/photo_backup_service.dart';

class SplashPage extends ConsumerStatefulWidget {
  const SplashPage({Key? key}) : super(key: key);

  @override
  ConsumerState<SplashPage> createState() => _SplashPageState();
}

class _SplashPageState extends ConsumerState<SplashPage>
    with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<double> _animation;

  @override
  void initState() {
    super.initState();

    _controller = AnimationController(
      duration: const Duration(seconds: 2),
      vsync: this,
    );

    // 创建透明度动画
    _animation = Tween<double>(
      begin: 0.0,
      end: 1.0,
    ).animate(CurvedAnimation(parent: _controller, curve: Curves.easeIn));

    // 启动动画
    _controller.forward();

    // 设置延时导航
    Timer(const Duration(seconds: 2), () {
      _checkAuthAndNavigate();
    });
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  // 检查认证状态并导航
  Future<void> _checkAuthAndNavigate() async {
    try {
      final bool isAuthenticated = await AuthService.isLoggedIn();

      if (isAuthenticated) {
        // 用户已登录，检查自动备份状态
        await _checkAutoBackupStatus();

        // 导航到主页
        if (mounted) {
          Navigator.of(context).pushReplacementNamed(Routes.fileUpload);
        }
      } else {
        // 未登录，导航到登录页
        if (mounted) {
          Navigator.of(context).pushReplacementNamed(Routes.login);
        }
      }
    } catch (e) {
      if (mounted) {
        Navigator.of(context).pushReplacementNamed(Routes.login);
      }
    }
  }

  // 检查自动备份状态
  Future<void> _checkAutoBackupStatus() async {
    final backupState = ref.read(photoBackupProvider);
    final photoBackupService = PhotoBackupService();

    // 检查自动备份是否开启
    if (photoBackupService.isAutoBackupEnabled(backupState)) {
      // 如果已开启，加载待备份文件
      final pendingAssets = await photoBackupService.getPendingBackupAssets(
        ref,
      );

      // 如果有待备份文件，启动备份
      if (pendingAssets.isNotEmpty) {
        await photoBackupService.startBatchUpload(ref, pendingAssets);
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: BoxDecoration(color: Theme.of(context).primaryColor),
        child: FadeTransition(
          opacity: _animation,
          child: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Image.asset('assets/images/logo.png', width: 120, height: 120),
                const SizedBox(height: 24),
                const Text(
                  '咕噜文件',
                  style: TextStyle(
                    fontSize: 24,
                    fontWeight: FontWeight.bold,
                    color: Colors.white,
                  ),
                ),
                const SizedBox(height: 12),
                const Text(
                  '安全高效的云存储',
                  style: TextStyle(fontSize: 16, color: Colors.white70),
                ),
                const SizedBox(height: 40),
                const CircularProgressIndicator(
                  valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
